package cn.microservices.cloud.system.web.controller;

import cn.microservices.cloud.common.core.utils.SoMap;
import cn.microservices.cloud.common.web.utils.CommonRequestUtils;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.ejlchina.okhttps.OkHttps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户操作
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Value("${microservices.header.from}")
    public String from;
    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("doLogin")
    public String doLogin(String username, String password, String loginType) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if("zhang".equals(username) && "123456".equals(password)) {
            StpUtil.stpLogic=new StpLogic(loginType);
            SaLoginModel saLoginModel =SaLoginModel.create();
            saLoginModel.device= CommonRequestUtils.getDevice();
            StpUtil.login(10001, saLoginModel);
            String tokenValue = StpUtil.getTokenValueByLoginId(10001);
            SaTokenInfo token = StpUtil.getTokenInfo();
            return "登录成功"+tokenValue+"|||||"+token.getTokenName();
        }
        return "登录失败";
    }

    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }


    // 相关参数配置
    private String clientId = "1001";								// 应用id
    private String clientSecret = "aaaa-bbbb-cccc-dddd-eeee";		// 应用秘钥
    private String serverUrl = "http://localhost:7000";	// 服务端接口

    // 模式三：密码式-授权登录
    @RequestMapping("/passwordLogin")
    public SaResult passwordLogin(String username, String password, String loginType) {
        // 模式三：密码式-授权登录
        String str = OkHttps.sync(serverUrl + "/oauth2/token")
                .addBodyPara("grant_type", "password")
                .addBodyPara("client_id", clientId)
                .addBodyPara("username", username)
                .addBodyPara("password", password)
                .addBodyPara("loginType", loginType)
                .addHeader("equipmentType",CommonRequestUtils.getDevice())
                .addHeader("from",from)
                .post()
                .getBody()
                .toString();
        SoMap so = SoMap.getSoMap().setJsonString(str);
        System.out.println("返回结果: " + so);

        // code不等于200  代表请求失败
        if(so.getInt("code") != 200) {
            return SaResult.error(so.getString("msg"));
        }

        // 根据openid获取其对应的userId
        SoMap data = so.getMap("data");
        long uid = getUserIdByOpenid(data.getString("openid"));
        data.set("uid", uid);

        // 返回相关参数
        StpUtil.login(uid);
        return SaResult.data(data);
    }

    // ------------ 模拟方法 ------------------
    // 模拟方法：根据openid获取userId
    private long getUserIdByOpenid(String openid) {
        // 此方法仅做模拟，实际开发要根据具体业务逻辑来获取userId
        return 10001;
    }
}
